package com.yunhai.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yunhai.common.dto.UserHolderDto;
import com.yunhai.common.utils.UserHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    public  MpMetaObjectHandler(){
        System.out.println("MpMetaObjectHandler~~~~");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        System.out.println("insertFill~~~~~~~");

        //添加时候自动填充 setFieldValByName三个参数为：映射类字段，填充值，原对象
        // setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
        //给createTime这个字段和updateTime这俩字段 来一个什么值呢 来一个自动插入时间 传一个数据 这个数据就是mataObject

        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(),   metaObject);
        this.setFieldValByName("createBy","zhangsan",metaObject);
        this.setFieldValByName("updateBy", "zhangsan",metaObject);

//        UserHolderDto user = (UserHolderDto)UserHolder.getUser();
//        if( user != null ){
//            this.setFieldValByName("createBy", user.getId(),metaObject);
//            this.setFieldValByName("updateBy", user.getId(),metaObject);
//        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(),  metaObject);
        UserHolderDto user = UserHolder.getUser();
        if( user != null ){
            this.setFieldValByName("updateBy", "zhangsan",metaObject);
        }
    }
}
